#!/usr/bin/env python3
"""
市场数据管理功能演示
展示新增的市场数据管理基础设施功能
"""

import asyncio
import os
import sys

# 设置环境变量
os.environ['ENVIRONMENT'] = 'development'
os.environ['JWT_SECRET'] = 'demo-secret-key'

# 添加enhanced目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'enhanced'))

from market_data import MarketDataManager, MarketDataError


async def demo_market_data_features():
    """演示市场数据管理功能"""
    print("🚀 加密货币市场数据管理功能演示")
    print("=" * 60)
    
    # 创建市场数据管理器
    manager = MarketDataManager()
    
    # 测试币种列表
    test_symbols = ['BTC', 'ETH', 'ADA']
    
    print("\n📊 1. 获取市场数据（多货币支持）")
    print("-" * 40)
    
    for symbol in test_symbols:
        try:
            data = await manager.get_market_data(symbol)
            
            print(f"\n💰 {symbol} 市场数据:")
            print(f"   市值排名: #{data['market_cap_rank']}")
            print(f"   市值 (USD): ${data['market_cap']['USD']:,.0f}")
            print(f"   市值 (EUR): €{data['market_cap']['EUR']:,.0f}")
            print(f"   市值 (CNY): ¥{data['market_cap']['CNY']:,.0f}")
            print(f"   24h交易量: ${data['volume_24h']['USD']:,.0f}")
            print(f"   交易量变化: {data['volume_change_24h']:+.2f}%")
            
        except MarketDataError as e:
            print(f"❌ 获取 {symbol} 数据失败: {e.message}")
    
    print("\n📈 2. 获取交易量数据")
    print("-" * 40)
    
    for symbol in test_symbols[:2]:  # 只测试前两个
        try:
            volume_data = await manager.get_volume_data(symbol)
            print(f"{symbol}: ${volume_data['volume_24h_usd']:,.0f} ({volume_data['volume_change_24h_percent']:+.2f}%)")
            
        except MarketDataError as e:
            print(f"❌ 获取 {symbol} 交易量失败: {e.message}")
    
    print("\n🏆 3. 获取市值排名")
    print("-" * 40)
    
    for symbol in test_symbols:
        try:
            rank = await manager.get_market_cap_rank(symbol)
            print(f"{symbol}: 排名 #{rank}")
            
        except MarketDataError as e:
            print(f"❌ 获取 {symbol} 排名失败: {e.message}")
    
    print("\n💱 4. 支持的货币列表")
    print("-" * 40)
    currencies = manager.get_supported_currencies()
    print(f"支持的货币: {', '.join(currencies)}")
    
    print("\n🗄️ 5. 数据库功能测试")
    print("-" * 40)
    
    # 测试数据清理功能
    try:
        cleanup_result = await manager.cleanup_old_data(days=30)
        print(f"数据清理完成:")
        print(f"  - 清理市场数据: {cleanup_result['market_data_deleted']} 条")
        print(f"  - 清理汇率数据: {cleanup_result['exchange_rates_deleted']} 条")
    except Exception as e:
        print(f"❌ 数据清理失败: {e}")
    
    print("\n✅ 6. 功能特性总结")
    print("-" * 40)
    features = [
        "✓ 市场数据获取 (市值、交易量、排名)",
        "✓ 多货币支持 (USD, EUR, CNY)",
        "✓ 智能缓存机制 (内存 + 数据库)",
        "✓ 数据库持久化存储",
        "✓ 异步操作支持",
        "✓ 错误处理和异常管理",
        "✓ 数据清理和维护功能"
    ]
    
    for feature in features:
        print(f"  {feature}")
    
    print("\n" + "=" * 60)
    print("🎉 市场数据管理功能演示完成！")
    print("📝 注意: 当前使用模拟数据，实际API集成将在后续任务中实现")


if __name__ == '__main__':
    asyncio.run(demo_market_data_features())